<template>
  <div class="upload-demo">
    <!-- 上传组件 -->
    <el-upload
      class="avatar-uploader"
      :show-file-list="false"
      :before-upload="beforeUpload"
    >
      <!-- 图片预览 -->
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>

    <!-- 上传提示 -->
    <div v-if="!imageUrl" class="upload-tip">
      点击上传头像
    </div>

    <!-- 上传进度 -->
    <div v-if="uploadProgress > 0" class="upload-progress">
      上传进度：{{ uploadProgress }}%
    </div>
  </div>
</template>

<script>
import { showMsg } from '@/utils/showMsg'
import { config } from '../../../config'
import { Plus } from '@element-plus/icons-vue' // 引入图标
import { uploadFile } from '@/services/qiniu' // 引入七牛云服务

export default {
  name: 'AvatarUpload',
  components: {
    Plus
  },
  data()
  {
    return {
      imageUrl: '', // 图片预览 URL
      uploadProgress: 0 // 上传进度
    }
  },
  methods: {
    // 上传前的钩子
    beforeUpload(file)
    {
      console.log('文件类型:', file.type) // 打印文件类型
      console.log('文件对象:', file) // 打印文件对象

      // 限制文件类型和大小
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage)
      
        showMsg('文件格式错误', '只能上传图片文件！', 'error')
      
      if (!isLt2M)
      
        showMsg('文件格式错误', '图片大小不能超过 2MB！', 'error')
      

      if (isImage && isLt2M)
      
        this.uploadFile(file) // 开始上传
      

      return false // 阻止默认上传行为
    },

    // 上传文件
    uploadFile(file)
    {
      console.log('上传文件对象:', file) // 打印文件对象

      uploadFile(
        file,
        (progress) =>
        {
          this.uploadProgress = Math.floor(progress.percent) // 更新上传进度
        },
        (result) =>
        {
          // 拼接图片 URL
          const domain = config.domain // 替换为你的七牛云外链域名
          this.imageUrl = `${domain}/${result.key}`
          showMsg('上传成功', '头像上传成功！', 'success')
          this.uploadProgress = 0 // 重置上传进度
        },
        (error) =>
        {
          showMsg('图片上传失败', `上传失败: ${error}`, 'error')
          this.uploadProgress = 0 // 重置上传进度
        }
      )
    }
  }
}
</script>

<style scoped>
.avatar-uploader {
  width: 150px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-tip {
  margin-top: 10px;
  font-size: 14px;
  color: #606266;
}

.upload-progress {
  margin-top: 10px;
  font-size: 14px;
  color: #409eff;
}
</style>
